/**
 * 员工选择
 */
App.directive("empSelect", [ "$rootScope", "$compile", "Page", function($rootScope, $compile, Page) {
    return {
        restrict: "A",
        scope: {
            model: "@ngModel",
            userId: "=edUser",
            deptId: "=edDept"
        },
        require: "ngModel",
        templateUrl: "views/directive/userSelect.html",
        controller: [ "$scope", "$element", function($scope, $element) {
            $scope.users = [], $scope.userSelected = [];
            $scope.treeId = Metronic.getUniqueID();
            $scope.showType = "org";
            $scope.treeSynCheck = function(source, dest) {
                var checkedNodes = source.getCheckedNodes(true);
                dest.setting.view.expandSpeed = "";
                dest.checkAllNodes(false);
                dest.expandAll(false);
                dest.setting.view.expandSpeed = "fast";
                $(checkedNodes).each(function(index, item) {
                    if (item.type == "emp") {
                        $(dest.getNodesByParam("id", item.id, null)).each(function(index2, node) {
                            if (node.deptid == item.deptid && node.posid == item.posid) {
                                dest.checkNode(node, true, true);
                            }
                        });
                    }
                });
                checkedNodes = dest.getCheckedNodes(true);
                var checkedLen = checkedNodes.length;
                if (checkedLen > 0) {
                    for (var i = 0; i < checkedLen; i++) {
                        dest.expandNode(checkedNodes[i], true);
                    }
                }
            };
            $scope.unselect = function(user) {
                $($scope.userSelected).each(function(index, item) {
                    if (item.id == user.id) {
                        $scope.userSelected.splice(index, 1);
                        return false;
                    }
                });
                var nodes = $scope.orgTree.getNodesByParam("id", user.id, null);
                $(nodes).each(function(index, node) {
                    $scope.orgTree.checkNode(node, false, true);
                });
                nodes = $scope.posTree.getNodesByParam("id", user.id, null);
                $(nodes).each(function(index, node) {
                    $scope.posTree.checkNode(node, false, true);
                });
            };
            $scope.select = function() {
                $scope._ok = true;
                $scope.modal.hide();
            };
            $scope.onHidden = function() {
                if ($scope._ok) {
                    $scope.users = angular.copy($scope.userSelected);
                    $scope.updateValue();
                    $scope._ok = false;
                } else {
                    $scope.userSelected = angular.copy($scope.users);
                    $scope.updateTree($scope.orgTree);
                    if ($scope.multiple) {
                        $scope.updateTree($scope.posTree);
                    }
                }
            };
            $scope.search = function() {
                Ztree.search($scope.orgTree, "searchKeys", $scope.userName, function(node) {
                    return node.type == "emp";
                });
            };
        } ],
        link: function(scope, elem, attrs, ngModelController) {
            var input = elem.find('input[type="text"]:eq(0)');
            if (attrs.edUser || attrs.edDept) {
                $(elem).find(".radio-inline:eq(1)").hide();
            }
            scope.multiple = attrs.edMultiple == "true";
            var setting = {
                check: {
                    enable: scope.multiple
                },
                view: {
                    selectedMulti: false,
                    fontCss: function(treeId, treeNode) {
                        return treeNode.highlight == "1" ? {
                            color: "#A60000",
                            "font-weight": "bold"
                        } : {
                            color: "#333",
                            "font-weight": "normal"
                        };
                    }
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: function(event, treeId, treeNode, clickFlag) {
                        if (!scope.multiple) {
                            if (treeNode.isParent) {
                                scope.orgTree.expandNode(treeNode);
                            } else {
                                if (treeNode.type == "emp") {
                                    scope.$apply(function() {
                                        scope.userSelected = [];
                                        scope.userSelected.push(treeNode);
                                    });
                                }
                            }
                        }
                    },
                    onDblClick: function(event, treeId, treeNode) {
                        if (!scope.multiple && treeNode.type == "emp") {
                            scope.select();
                        }
                    },
                    onCheck: function(event, treeId, treeNode) {
                        var source;
                        if (treeId == "orgTree" + scope.treeId) {
                            source = scope.orgTree;
                            scope.treeSynCheck(scope.orgTree, scope.posTree);
                        } else {
                            source = scope.posTree;
                            scope.treeSynCheck(scope.posTree, scope.orgTree);
                        }
                        scope.$apply(function() {
                            $(getChildren(treeNode)).each(function(index, relative) {
                                if (relative.type == "emp") {
                                    if (relative.checked) {
                                        if (!contains(relative)) {
                                            scope.userSelected.push(relative);
                                        }
                                    } else {
                                        $(scope.userSelected).each(function(index1, user) {
                                            if (relative.id == user.id) {
                                                var have = false;
                                                $(source.getNodesByParam("id", relative.id, null)).each(function(index2, node) {
                                                    if (!(node.deptid == relative.deptid && node.posid == relative.posid) && node.checked) {
                                                        have = true;
                                                    }
                                                });
                                                if (!have) {
                                                    scope.userSelected.splice(index1, 1);
                                                }
                                                return false;
                                            }
                                        });
                                    }
                                }
                            });
                        });
                    }
                }
            };
            var key = "_userTree:" + (scope.deptId || "") + ":" + (scope.userId || "");
            if ($rootScope[key]) {
                scope.data = $rootScope[key];
            } else {
                Page.ajaxPost("employee/tree.do", {
                    deptId: scope.deptId,
                    userId: scope.userId
                }, function(response) {
                    $rootScope[key] = response.data;
                    scope.data = $rootScope[key];
                    if (!angular.isUndefined(ngModelController.$viewValue)) {
                        ngModelController.$render();
                    }
                });
            }
            scope.onShow = function() {
                if (!scope.orgTree) {
                    var orgTree = $(elem).find(".ztree:eq(0)").attr("id", "orgTree" + scope.treeId);
                    var posTree = $(elem).find(".ztree:eq(1)").attr("id", "posTree" + scope.treeId);

                    $(scope.data.org).each(function(index, emp) {
                        if(emp.type == 'dept'){
                            emp.iconOpen = '././assets/admin/img/system/folder_open.png';
                            emp.iconClose = '././assets/admin/img/system/folder_close.png';
                            emp.icon = '././assets/admin/img/system/folder_close.png';
                        }else if(emp.type == 'emp'){
                            emp.icon = '././assets/admin/img/system/emp.png';
                        }
                    });

                    scope.orgTree = $.fn.zTree.init(orgTree, setting, scope.data.org);
                    Ztree.expandRoot(scope.orgTree);
                    if (scope.multiple) {
                        scope.posTree = $.fn.zTree.init(posTree, setting, scope.data.pos);
                        Ztree.expandRoot(scope.posTree);
                    }
                }
                if (scope.needInitTree) {
                    scope.updateTree(scope.orgTree);
                    if (scope.multiple) {
                        scope.updateTree(scope.posTree);
                    }
                }
            };
            scope.updateValue = function() {
                var users = [];
                $(scope.users).each(function(index, user) {
                    users.push(user.id);
                });
                if (scope.multiple) {
                    ngModelController.$setViewValue(users.join(","));
                } else {
                    ngModelController.$setViewValue(users.length > 0 ? users[0] : "");
                }
                ngModelController.$render(true);
            };
            scope.updateTree = function(ztree) {
                scope.needInitTree = false;
                ztree.setting.view.expandSpeed = "";
                ztree.checkAllNodes(false);
                ztree.expandAll(false);
                ztree.setting.view.expandSpeed = "fast";
                if (!angular.isUndefined(ngModelController.$viewValue) && ngModelController.$viewValue.length > 0) {
                    if (!scope.multiple) {
                        var node = ztree.getNodeByParam("id", ngModelController.$viewValue, null);
                        ztree.selectNode(node, false);
                        ztree.expandNode(node, true);
                    } else {
                        $.each(ngModelController.$viewValue.split(","), function(index, id) {
                            var node = ztree.getNodeByParam("id", id, null);
                            if (node && node.type == "emp") {
                                ztree.checkNode(node, true, true);
                            }
                        });
                        var checkedNodes = ztree.getCheckedNodes(true), checkedLen = checkedNodes.length;
                        if (checkedLen > 0) {
                            for (var i = 0; i < checkedLen; i++) {
                                ztree.expandNode(checkedNodes[i], true);
                            }
                        }
                    }
                }
            };
            ngModelController.$render = function(isUpdateViewOnly) {
                if (!isUpdateViewOnly && !angular.isUndefined(scope.data)) {
                    var tmpArr = (ngModelController.$viewValue || "").replace(/ /g, "").split(",");
                    if (tmpArr.length > 0) {
                        var ids = "," + tmpArr.join(",") + ",";
                        $(scope.data.org).each(function(index, user) {
                            if (ids.indexOf("," + user.id + ",") >= 0 && !contains(user)) {
                                $(tmpArr).each(function(index1, id) {
                                    if (id == user.id) {
                                        tmpArr[index1] = user;
                                    }
                                });
                            }
                        });
                    }
                    scope.userSelected = tmpArr;
                    scope.users = angular.copy(scope.userSelected);
                    scope.needInitTree = true;
                }
                if (scope.users.length == 0) {
                    input.val("");
                } else {
                    var names = [];
                    $(scope.users).each(function(index, user) {
                        names.push(user.name);
                    });
                    input.val(names.join(", "));
                }
            };
            function getChildren(treeNode) {
                var arr = [];
                arr.push(treeNode);
                if (treeNode.isParent) {
                    for (var obj in treeNode.children) {
                        arr = arr.concat(getChildren(treeNode.children[obj]));
                    }
                }
                return arr;
            }
            function contains(user) {
                var flag = false;
                $(scope.userSelected).each(function(index, user1) {
                    if (user1.id == user.id) {
                        flag = true;
                        return false;
                    }
                });
                return flag;
            }
        }
    };
} ]);
